package com.j.lemon.learn.thread.ThreadControl;

/**
 * @Author lijunjun
 * @Date 2019-04-02 10:43
 * @Description Object.wait(),Object.notify() ,可以实现两个线程交替执行,wait 和 notify只能在synchronize代码块中使用，
 *              wait 和 notify 是 object 类的方法，wait会释放当前锁，直到这个对象(被锁住的对象)调用了notify方法。下面是交替打印的一个例子
 */
public class AlternatePrinting1 {
    private static volatile int num;
    private static final Object lock = new Object();

    private static void print() throws InterruptedException {
        synchronized (lock){
            lock.notify();
            System.out.println(Thread.currentThread().getName()+"print");
            lock.wait();
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {
            new Thread(()->{
                for (int j = 0; j < 10; j++) {
                    try {
                        print();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }).start();
        }

    }
}
